﻿using Flee.PublicTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TruckScale.Models;

namespace TruckScale.Helpers
{
  public static class FleeHelper
  {
    public static string FormulaCalc(WeighRecordModel weighRecord, string expression)
    {
      //备用字段公式计算
      ExpressionContext context = new ExpressionContext();
      context.Imports.AddType(typeof(Math));
      string rst = string.Empty;

      try
      {
        context.Variables["_mz"] = Convert.ToDecimal(weighRecord.Mz);
        context.Variables["_pz"] = Convert.ToDecimal(weighRecord.Pz);
        context.Variables["_jz"] = Convert.ToDecimal(weighRecord.Jz);
        context.Variables["_dj"] = weighRecord.Dj;

        var properties = weighRecord.GetType().GetProperties().Where(prop => prop.Name.StartsWith("By"));

        foreach (var property in properties)
        {
          string variableName = "_" + property.Name.ToLower();
          decimal value = 0;
          decimal.TryParse(property.GetValue(weighRecord)?.ToString(), out value);
          
          context.Variables[variableName] = value;
        }
      }
      catch (Exception ex)
      {
        throw new Exception($"数值转换异常: {ex.Message}", ex);
      }

      try
      {
        IDynamicExpression eDynamic = context.CompileDynamic(expression);
        rst = eDynamic.Evaluate().ToString();
      }
      catch (ExpressionCompileException ex)
      {
        throw new Exception($"计算异常: {ex.Message}", ex);
      }

      return rst;
    }
  }
}
